<?php

namespace app\master\controller;

use think\Db;
use think\Exception;

class Carmanage extends Base
{
    //车辆状态
    public function carstatus()
    {
        if (request()->isGet()) {
            return $this->fetch('carstatus');
        }
        $page = input("page");
        $limit = input("limit");
        $field = "c.store_id,c.car_id,c.car_name,c.car_type,c.car_plate,c.car_who,c.car_types,c.car_hangup,c.is_secular,from_unixtime(c.start_time,'%Y .%m .%d') as start_time,from_unixtime(c.end_time,'%Y .%m .%d') as end_time,s.store_name,c.location_store_id";
        $list = model('carmanage')->carstatuslist($field, $page, $limit);
        $is_store = session('is_store');
        $list['data'] = storeEdit($is_store, $list['data']);
        return $this->tableReturn(0, '查询成功', $list['count'], $list['data']);
    }

    //修改车辆状态
    public function updStatus()
    {
        $car_id = input('car_id');
        $type = input('type');
        $res = db('car')->where('car_id', $car_id)->update(['car_types' => $type]);
        if ($res) $this->ajaxReturn(200, '操作成功');
        else $this->ajaxReturn(603, '系统繁忙');
    }

    //添加车辆
    public function addcar()
    {
        if (request()->isGet()) {
            $store = db("store")->select();
            $this->assign("store", $store);
            $cartype = model('carmanage')->gettypelist(['pid' => 0]);
            $this->assign('cartype', $cartype);
            return $this->fetch("addcar");
        }
        $data = input("post.");
        if (empty($data["img"])) $this->ajaxReturn(603, '请选择图片！');
        if ($data['is_secular'] == 2) {
            if (!$data['start_time'] || !$data['end_time']) $this->ajaxReturn(603, '请选择开始时间与结束时间');
        }
        $cartype = db('cartype')->where('cartype_id', $data['cartype_id'])->value('cartype_what');
        $cartypes = db('cartype')->where('cartype_id', $data['cartype_ids'])->value('cartype_what');
        $car = [
            "car_name" => $cartype . $cartypes,
            "car_type" => $data['car_type'],
            "car_plate" => $data['car_plate'],
            "car_who" => $data['car_who'],
            "car_types" => 1,
            "store_id" => $data['store_id'],
            "car_color" => $data['car_color'],
            "car_riskover" => strtotime($data['car_riskover']),
            "car_hangup" => $data['car_hangup'],
            "car_yearover" => strtotime($data['car_yearover']),
            "car_lastmaintain" => strtotime($data['car_lastmaintain']),
            "car_seeworldtime" => strtotime($data['car_seeworldtime']),
            "car_status" => 1,
            "cartype_id" => $data['cartype_id'],
            "cartype_ids" => $data['cartype_ids'],
            'is_secular' => $data['is_secular'],
            'start_time' => strtotime($data['start_time']),
            'end_time' => strtotime($data['end_time']),
            'engineno' => $data['engineno'],
            'classno' => $data['classno'],
        ];
        //缩略图
        $path = config("TEMPORARY_CATALOG_FILE_PATH") . getFileName($data["img"]);
        $res = moveFile($path, config("CAR_FILE_PATH"));
        if (!$res) $this->ajaxReturn(603, selectFile);
        Db::startTrans();
        try {
            $carid = db("car")->insertGetId($car);
            $carimg = [
                'car_id' => $carid,
                'car_img' => $res,
            ];
            db("CarImg")->insert($carimg);
            Db::commit();
            $this->ajaxReturn(200, successMsg, url("Carmanage/carstatus"));
        } catch (\Exception $e) {
            Db::rollback();
            $this->ajaxReturn(603, errorMsg);
        }
    }

    //修改车辆
    public function updCar()
    {
        if (request()->isGet()) {
            $id = input('car_id');
            $carimg = db("CarImg")->where('car_id', $id)->find();
            $car = db('car')->where('car_id', $id)->find();
            $store = db("store")->select();
            $cartype = model('carmanage')->gettypelist(['pid' => 0]);
            $cartwotype = model('carmanage')->gettypelist(['pid' => ['not in', 0]]);
            $this->assign("car", $car);
            $this->assign("store", $store);
            $this->assign("carimg", $carimg);
            $this->assign('cartype', $cartype);
            $this->assign('cartwotype', $cartwotype);
            return $this->fetch('updcar');
        }
        $data = input();
        if ($data['is_secular'] == 2) {
            if (!$data['start_time'] || !$data['end_time']) $this->ajaxReturn(603, '请选择开始时间与结束时间');
        } else {
            $data['start_time'] = null;
            $data['end_time'] = null;
        }
        $cartype = db('cartype')->where('cartype_id', $data['cartype_id'])->value('cartype_what');
        $cartypes = db('cartype')->where('cartype_id', $data['cartype_ids'])->value('cartype_what');
        $car = [
            "car_id" => $data['car_id'],
            "car_name" => $cartype . $cartypes,
            "car_type" => $data['car_type'],
            "car_plate" => $data['car_plate'],
            "car_who" => $data['car_who'],
            "store_id" => $data['store_id'],
            "car_color" => $data['car_color'],
            "car_riskover" => strtotime($data['car_riskover']),
            "car_hangup" => $data['car_hangup'],
            "car_yearover" => strtotime($data['car_yearover']),
            "car_lastmaintain" => strtotime($data['car_lastmaintain']),
            "car_seeworldtime" => strtotime($data['car_seeworldtime']),
            "cartype_id" => $data['cartype_id'],
            "cartype_ids" => $data['cartype_ids'],
            'is_secular' => $data['is_secular'],
            'start_time' => strtotime($data['start_time']),
            'end_time' => strtotime($data['end_time']),
            'engineno' => $data['engineno'],
            'classno' => $data['classno'],
        ];
        if (!empty($data["img"])) {
            $oldPath = config("TEMPORARY_CATALOG_FILE_PATH") . getFileName($data["img"]);
            $newPath = config("CAR_FILE_PATH");
            $path = moveFile($oldPath, $newPath);
            if (!$path) $this->ajaxReturn(603, selectFile);
            $carimg["car_img"] = $path;
            $carimg["car_img_id"] = $data['car_img_id'];
            db('car_img')->update($carimg);
        }
        $res = db("car")->update($car);
        if ($res) $this->ajaxReturn(200, successMsg, url("Carmanage/carstatus"));
        else $this->ajaxReturn(603, errorMsg);
    }

    //私家车审核列表
    public function oneselfcar()
    {
        if (request()->isGet()) {
            return $this->fetch('oneselfcar');
        }
        $page = input("page");
        $limit = input("limit");
        $list = model('carmanage')->oneselfcar($page, $limit);
        return $this->tableReturn(0, '查询成功', $list['count'], $list['data']);
    }

    //同意审核
    public function agreeapplycar()
    {
        $oneselfcar_id = input('oneselfcar_id');
        $data = db('oneselfcar')->where('oneselfcar_id', $oneselfcar_id)->find();
        if ($data['oneselfcar_status'] != 1) $this->ajaxReturn(603, "您不可执行此操作");
        $car = [
            "car_name" => $data['oneselfcar_name'],
            "car_type" => $data['oneselfcar_types'],
            "car_plate" => $data['oneselfcar_plate'],
            "car_who" => 3,
            "store_id" => $data['store_id'],
            "car_color" => $data['oneselfcar_color'],
            "car_riskover" => $data['oneselfcar_riskover'],
            "car_hangup" => $data['oneselfcar_hangup'],
            "car_yearover" => $data['oneselfcar_yearover'],
            "car_lastmaintain" => $data['oneselfcar_lastmaintain'],
            "car_seeworldtime" => $data['oneselfcar_seeworldtime'],
            "car_types" => 1,
            "car_status" => 1,
        ];
        Db::startTrans();
        try {
            db('car')->insert($car);
            db('oneselfcar')->where('oneselfcar_id', $oneselfcar_id)->update(['oneselfcar_status' => 2]);
            Db::commit();
            $this->ajaxReturn(200, successMsg, url("Carmanage/oneselfcar"));
        } catch (\Exception $e) {
            Db::rollback();
            $this->ajaxReturn(603, errorMsg);
        }
    }

    //拒绝审核
    public function refuseapplycar()
    {
        $oneselfcar_id = input('oneselfcar_id');
        $data = db('oneselfcar')->where('oneselfcar_id', $oneselfcar_id)->find();
        if ($data['oneselfcar_status'] != 1) $this->ajaxReturn(603, "您不可执行此操作");
        $list = db('oneselfcar')->where('oneselfcar_id', $oneselfcar_id)->update(['oneselfcar_status' => 3]);
        if ($list) {
            $this->ajaxReturn(200, successMsg, url("Carmanage/oneselfcar"));
        } else {
            $this->ajaxReturn(603, errorMsg);
        }
    }

    //车辆型号
    public function cartype()
    {
        if (request()->isGet()) {
            return $this->fetch('cartype');
        }
        $page = input("page");
        $limit = input("limit");
        $list = model('carmanage')->cartype($page, $limit);
        return $this->tableReturn(0, '查询成功', $list['count'], $list['data']);
    }

    //添加品牌
    public function addcartype()
    {
        $this->view->engine->layout(false);
        if (request()->isGet()) {
            return $this->fetch("addcartype");
        }
        $cartype_what = input('cartype_what');
        $cartype = [
            "cartype_what" => $cartype_what,
            "cartype_time" => time(),
            "pid" => 0,
            "cartype_status" => 1,
        ];
        $add = db("cartype")->insert($cartype);
        if ($add) {
            $this->ajaxReturn(200, "添加成功");
        } else {
            $this->ajaxReturn(603, "添加失败");
        }
    }

    //添加型号
    public function addcartypes()
    {
        $this->view->engine->layout(false);
        if (request()->isGet()) {
            $cartype = db("cartype")->where('pid', 0)->select();
            $this->assign("cartype", $cartype);
            return $this->fetch("addcartypes");
        }
        $cartype_what = input('cartype_what');
        $cartype_pid = input('cartype_id');
        $cartype = [
            "cartype_what" => $cartype_what,
            "cartype_time" => time(),
            "pid" => $cartype_pid,
            "cartype_status" => 1,
        ];
        $add = db("cartype")->insert($cartype);
        if ($add) {
            $this->ajaxReturn(200, "添加成功");
        } else {
            $this->ajaxReturn(603, "添加失败");
        }
    }

    //删除品牌或型号
    public function delcartype()
    {
        $cartype_id = input('cartype_id');
        $isfu = db('cartype')->where('cartype_id', $cartype_id)->value('pid');
        if ($isfu == 0) {
            $isson = db('cartype')->where('pid', $cartype_id)->count();
            if ($isfu == 0 && $isson > 0) $this->ajaxReturn(603, "此品牌不可删除");
        }
        $del = db('cartype')->where('cartype_id', $cartype_id)->update(['cartype_status' => 2]);
        if ($del) {
            $this->ajaxReturn(200, "删除成功");
        } else {
            $this->ajaxReturn(603, "删除失败");
        }
    }

    //违章
    public function recordViolation()
    {
        if (request()->isGet()) {
            return $this->fetch('recordviolation');
        }
    }

    //违章查询
    public function recordViolationCar()
    {
        header("content-Type: text/html; charset=UTF-8");
        if (request()->isGet()) {
            return $this->fetch('recordviolationcar');
        }
        $appkey = config('WZAAPPKEY');
        $city = config('WZAADDRESS');
        $page = input('page');
        $limit = input('limit');

        $where = [
            'car_status' => 1,
        ];
        $is_store = session('is_store');
        if ($is_store == 1) {
            $admin_id = session('admin_id');
            $store_id = model('Store')->getStoreId($admin_id);
            $where['store_id'] = $store_id;
        }
        $car = db('car')->field("*,from_unixtime(car_yearover,'%Y .%m .%d %H:%i:%s') as car_yearover")->where($where)->page($page, $limit)->order('car_id desc')->select();
        $count = db('car')->where($where)->count();
        foreach ($car as $k => $v) {
            $car[$k]['car_no'] = urlencode($car[$k]['car_plate']);
            $car[$k]['wzinfo'] = getWz($appkey, $city, $car[$k]['car_no'], $car[$k]['engineno'], $car[$k]['classno']);
        }
        return $this->tableReturn(0, '查询成功', $count, $car);
    }

    //还车审核
    public function returnCarList()
    {
        if (request()->isGet()) {
            return $this->fetch('returncar');
        }
        $where = [
            'co.status' => ['in',[1,2]],
        ];
        $is_store = session('is_store');
        if ($is_store == 1) {
            $admin_id = session('admin_id');
            $store_id = model('Store')->getStoreId($admin_id);
            $where['co.store_id'] = $store_id;
        }
        $page = input('page');
        $limit = input('limit');
        $field = 'c.car_plate,concat(ct.cartype_what,ctp.cartype_what) as cartype_what,co.company_name,m.member_name,m.member_tel,s.store_name,st.store_name as j_store_name,co.apply_car_id,co.status,from_unixtime(co.create_time,\'%Y.%m.%d %H:%i:%s\') as apply_time';
        //echo $field;die;
        $list = model('Contractcar')->getReturnCar($field, $where, $page, $limit);
        return $this->tableReturn(0, '查询成功', $list['count'], $list['data']);
    }

    //归还车辆
    public function returnCar()
    {
        $id = input('id');
        $find = db('apply_car')->where('apply_car_id', $id)->find();
        if ($find['status'] == 2) $this->ajaxReturn(603, '系统繁忙，请稍后再试');
        Db::startTrans();
        try {
            db('apply_car')->where('apply_car_id', $id)->update(['status' => 2]);
            db('car')->where('car_id', $find['car_id'])->update(['car_types' => 1,'company_id'=>null, 'location_store_id' => $find['store_id']]);
            Db::commit();
            $this->ajaxReturn(200, '操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            $this->ajaxReturn(603, '系统繁忙，请稍后再试');
        }
    }

    //拒绝车辆归还
    public function refuseCar()
    {
        $id = input('id');
        $res = db('apply_car')->where('apply_car_id', $id)->update(['status' => 1]);
        if ($res) $this->ajaxReturn(200, '操作成功');
        else $this->ajaxReturn(603, '系统繁忙，请稍后再试');
    }

    //车辆调拨申请列表
    public function allocation()
    {
        if (request()->isGet()) {
            return $this->fetch('allocation');
        }
        $where = [
            'c.car_types' => 1,
            // 'c.location_store_id|c.store_id'=>1
        ];
        $is_store = session('is_store');
        if ($is_store == 1) {
            $admin_id = session('admin_id');
            $store_id = model('Store')->getStoreId($admin_id);
            $where['c.location_store_id|c.store_id'] = $store_id;
        }
        $field = "c.car_id,c.car_plate,concat(ca.cartype_what,ct.cartype_what) as cartype_what,s.store_name";
        $page = input('page');
        $limit = input('limit');
        $list = model('Car')->getLocationStoreCar($field, $where, $page, $limit);
        return $this->tableReturn(0, '查询成功', $list['count'], $list['data']);
    }

    //调拨申请
    public function applyAllocation()
    {
        $this->view->engine->layout(false);
        $admin_id = session('admin_id');
        $store_id = model('Store')->getStoreId($admin_id);
        if (request()->isGet()) {
            $id = input('id');
            $where = [
                's.store_id' => ['not in', $store_id],
                'a.status' => 1,
            ];
            $store = model('Store')->getStoreList($where);
            $this->assign('id', $id);
            $this->assign('store', $store);
            return $this->fetch('applyallocation');
        }
        $data = input();
        $data['call_store_id'] = $store_id;
        $data['create_time'] = time();
        //修改汽车状态调拨中
        db('car')->where('car_id', $data['car_id'])->update(['car_types' => 5]);
        $res = db('allocation')->insert($data);
        if ($res) $this->ajaxReturn(200, '操作成功');
        else $this->ajaxReturn(603, '系统繁忙，请稍后再试');
    }

    //车辆调拨接受
    public function acceptTransfer()
    {
        if (request()->isGet()) {
            return $this->fetch('accepttransfer');
        }
        $page = input('page');
        $limit = input('limit');
        $where = [
            // 'a.accept_store_id'=>$store_id,
            'a.status' => 1,
        ];
        $is_store = session('is_store');
        if ($is_store == 1) {
            $admin_id = session('admin_id');
            $store_id = model('Store')->getStoreId($admin_id);
            $where['a.accept_store_id'] = $store_id;
        }
        $field = "c.car_plate,concat(ca.cartype_what,ct.cartype_what) as cartype_what,sto.store_name,s.store_name as d_store_name,a.allocation_remarks,a.allocation_id,from_unixtime(a.create_time,'%Y.%m.%d %H:%i:%s') as create_time";
        $list = model('Car')->getAcceptTransfer($field, $where, $page, $limit);
        return $this->tableReturn(0, '查询成功', $list['count'], $list['data']);
    }

    //接收调拨
    public function agreeAllocation()
    {
        $id = input('id');
        $find = db('allocation')->where('allocation_id', $id)->find();
        if ($find['status'] == 2) $this->ajaxReturn(603, '系统繁忙，请稍后再试');
        db('car')->where('car_id', $find['car_id'])->update(['car_types' => 1]);
        $res = db('allocation')->where('allocation_id', $id)->update(['status' => 2, 'agree_time' => time()]);
        if ($res) $this->ajaxReturn(200, '操作成功');
        else $this->ajaxReturn(603, '系统繁忙，请稍后再试');
    }

    //车辆调拨记录
    public function allocationLog()
    {
        if (request()->isGet()) {
            return $this->fetch('allocationlog');
        }
        $admin_id = session('admin_id');
        $store_id = model('Store')->getStoreId($admin_id);
        $page = input('page');
        $limit = input('limit');
        $where = [
            //'a.accept_store_id|a.call_store_id'=>$store_id,
            'a.status' => 2,
        ];
        $is_store = session('is_store');
        if ($is_store == 1) {
            $admin_id = session('admin_id');
            $store_id = model('Store')->getStoreId($admin_id);
            $where['a.accept_store_id|a.call_store_id'] = $store_id;
        }

        $field = "c.car_plate,concat(ca.cartype_what,ct.cartype_what) as cartype_what,sto.store_name,s.store_name as d_store_name,st.store_name as j_store_name,a.allocation_remarks,a.allocation_id,from_unixtime(a.agree_time,'%Y.%m.%d %H:%i:%s') as agree_time,a.accept_store_id,a.call_store_id,a.status";
        $list = model('Car')->getAcceptTransfer($field, $where, $page, $limit);
        if ($is_store == 1) {
            foreach ($list['data'] as $k => $v) {
                if ($list['data'][$k]['accept_store_id'] == $store_id) {
                    $list['data'][$k]['type'] = 2;//接受
                } elseif ($list['data'][$k]['call_store_id'] == $store_id) {
                    $list['data'][$k]['type'] = 1;//调出
                }
            }
        }
        return $this->tableReturn(0, '查询成功', $list['count'], $list['data']);
    }


}